<?php

Session_Start();

require_once("config.php");
require_once("function.php");
require_once('File/Util.php');

if($_SESSION["login"] != "logged")
{
	Header("Location:$URL");
	die();
}

$action = $_REQUEST['action'];
if(empty($action)) {
	$action = 'ls';
}

$value = $_REQUEST['val'];

switch($action) {
	case 'ls':
		$dir = EDIT_ROOT . $value;
		if(substr($value, -2) == '..') {
			$value = dirname(dirname($value));
			$value = str_replace('\\', '/', $value);
			$dir = EDIT_ROOT . $value;
		}
        checkAccessAble($dir);
	   
		$dir = preg_replace('/\/{2,}/', '/', $dir);
		$showUp = $dir != EDIT_ROOT;
		if(is_dir($dir)) {
			echo dirJson($dir, $value, $showUp);
		} else {
			echo "{'error':'$value is not a dir.'}";
		}

		break;

	case 'open':
		$file = EDIT_ROOT . $value;
        checkAccessAble($file);
		if(is_file($file)) {
			echo GetFile($file);
		}
		else {
			echo "$value is not a file";
		}
		
		break;

	case 'save':
		$file = EDIT_ROOT . $value;
        checkAccessAble($file);
		if(!isset($_POST['content']) || !is_file($file)) {
			die('1');
		}

		$code = writeFile($file, stripslashes($_POST['content']));
		if($code == 1) {
			echo "1";
		}
		else {
			echo $code;
		}
		break;

    case 'new':
        if(!isset($_REQUEST['name'])) {
            die('1');
        }
        $file = EDIT_ROOT . $value;
        echo createNewFile($_REQUEST['name'], $file);
        break;
}

function checkAccessAble($path) {
    if( !File_Util::pathInRoot($path, EDIT_ROOT) ) {
        die('Access forbidden!');
    }
}

?>
